<template>
  <div class="admin">
    <a-row :gutter="24">
      <a-col :span="10">
        <a-card hoverable :bordered="false">
          <div class="admin-info">
            <div class="avatar">
              <img class="avatar-img" :src="user.avatar" alt="" />
            </div>
            <div class="admin-name">
              {{ user.name }}
            </div>
            <div class="admin-project project-name">
              <span>项目名称：</span>
              <span>{{ user.project[0].name }}</span>
            </div>
            <div class="admin-project project-id">
              <span> 项目id： </span>
              <span>
                {{ user.project[0].id }}
              </span>
            </div>
            <div class="option-btns">
              <a-button
                type="primary"
                style="margin-right: 8px; margin-top: 8px"
                icon="edit"
                @click="openinfo"
              >
                修改个人信息
              </a-button>
              <a-button
                type="primary"
                style="margin-right: 8px; margin-top: 8px"
                icon="lock"
                @click="openPwd"
              >
                修改密码
              </a-button>
              <a-button
                type="primary"
                style="margin-right: 8px; margin-top: 8px"
                icon="edit"
                @click="openName"
              >
                修改项目名称
              </a-button>
            </div>
          </div>
        </a-card>
      </a-col>
    </a-row>

    <a-modal class="edit-classify" title="修改密码" v-model="editPwd">
      <a-form
        :form="form"
        @submit="aaa"
        :label-col="{ span: 24 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-form-item>
          <a-input
            size="default"
            placeholder="请输入旧密码"
            autocomplete="autocomplete"
            type="password"
            v-decorator="[
              'oldPassword',
              {
                rules: [
                  { required: true, message: '请输入旧密码' },
                  {
                    pattern: /^[a-zA-Z0-9_-]{6,32}$/g,
                    message: '密码必须为6-32位的字母数字组合',
                  },
                ],
              },
            ]"
          >
            <a-tooltip slot="suffix" :title="pwdtips">
              <a-icon type="info-circle" style="color: rgba(0, 0, 0, 0.45)" />
            </a-tooltip>
          </a-input>
        </a-form-item>
        <a-form-item>
          <a-input
            size="default"
            placeholder="请输入新密码"
            autocomplete="autocomplete"
            type="password"
            v-decorator="[
              'newPassword',
              {
                rules: [
                  { required: true, message: '请输入新密码' },
                  {
                    pattern: /^[a-zA-Z0-9_-]{6,32}$/g,
                    message: '密码必须为6-32位的字母数字组合',
                  },
                ],
              },
            ]"
          >
            <a-tooltip slot="suffix" :title="pwdtips">
              <a-icon type="info-circle" style="color: rgba(0, 0, 0, 0.45)" />
            </a-tooltip>
          </a-input>
        </a-form-item>
      </a-form>
      <template slot="footer">
        <a-button @click="cancel"> 取消 </a-button>
        <a-button type="primary" @click="aaa"> 确认 </a-button>
      </template>
    </a-modal>
    <a-modal class="edit-admininfo" title="修改个人信息" v-model="editinfo">
      <div class="modal-name">
        用户名:
        <a-input style="width: 16rem" v-model="adminInfo.name"
          ><a-tooltip slot="suffix" :title="nametips">
            <a-icon type="info-circle" style="color: rgba(0, 0, 0, 0.45)" />
          </a-tooltip>
        </a-input>
      </div>
      <div class="modal-avatar">
        <span class="avatar-desc">头像:</span>
        <a-upload
          name="avatar"
          list-type="picture-card"
          class="avatar-uploader"
          :show-upload-list="false"
          :action="uploadUrl"
          :before-upload="beforeUpload"
          @change="handleChange"
        >
          <img v-if="imageUrl" :src="imageUrl" alt="avatar" />
          <div v-else>
            <a-icon :type="loading ? 'loading' : 'plus'" />
            <div class="ant-upload-text">Upload</div>
          </div>
        </a-upload>
      </div>

      <template slot="footer">
        <a-button @click="cancel"> 取消 </a-button>
        <a-button type="primary" @click="send"> 提交 </a-button>
      </template>
    </a-modal>
    <a-modal class="edit-admininfo" title="修改项目信息" v-model="editPro">
      <div class="modal-name">
        项目名称:
        <a-input style="width: 16rem" v-model="adminInfo.project[0].name"
          ><a-tooltip slot="suffix" :title="nametips">
            <a-icon type="info-circle" style="color: rgba(0, 0, 0, 0.45)" />
          </a-tooltip>
        </a-input>
      </div>
      <template slot="footer">
        <a-button @click="cancel"> 取消 </a-button>
        <a-button type="primary" @click="confirmPro"> 提交 </a-button>
      </template>
    </a-modal>
  </div>
</template>

<script>
function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener("load", () => callback(reader.result));
  reader.readAsDataURL(img);
}
import { logout } from "@/services/user";
import { mapMutations, mapGetters } from "vuex";
import { UPLOAD } from "@/services/api";
import { editProjectApi } from "@/services/dataSource";
import { editInfoApi, resetPwdApi } from "@/services/adminInfo";
export default {
  beforeCreate() {
    this.form = this.$form.createForm(this);
  },
  data() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
      },
      nametips: "中英文组成，长度1-16位",
      editinfo: false,
      pwdtips: "只能由英文、数字、下划线组成，且大于6位并小于32位长度",
      loading: false,
      editPwd: false,
      editPro: false,
      imageUrl: "",
      uploadUrl: "",
      headers: "",
      adminInfo: {},
      nameModal: false,
    };
  },
  computed: {
    ...mapGetters("account", ["user"]),
  },
  created() {
    this.imageUrl = this.user.avatar;
    this.headers = JSON.parse(localStorage.getItem("user")).token;
    this.adminInfo = JSON.parse(localStorage.getItem("user"));
  },
  mounted() {
    this.uploadUrl = UPLOAD;
  },
  methods: {
    async confirmPro() {
      await editProjectApi({
        projectId: this.adminInfo.project[0].id,
        projectName: this.adminInfo.project[0].name,
      });
      await this.setUser(this.adminInfo);
      this.$message.success("成功修改项目名称", 1);
      this.editPro = false;
    },
    openName() {
      this.editPro = true;
    },
    openPwd() {
      this.editPwd = true;
    },
    openinfo() {
      this.editinfo = true;
    },
    cancel() {
      this.editinfo = false;
      this.editPwd = false;
      this.editPro = false;
    },
    editName() {
      this.editPro = true;
    },
    aaa(e) {
      e.preventDefault();
      this.form.validateFields(async (err) => {
        if (!err) {
          try {
            const oldPassword = this.form.getFieldValue("oldPassword");
            const newPassword = this.form.getFieldValue("newPassword");
            await resetPwdApi(oldPassword, newPassword);
            this.$message.success({
              content: "密码修改成功，请重新登录",
              duration: 1,
              onClose: () => {
                logout();
                this.$router.replace("/login");
              },
            });
          } catch (error) {
            this.editPwd = false;
            this.$message.error(`修改失败,${error.msg}`, 1.5);
          }
        }
      });
    },
    ...mapMutations("account", ["setUser"]),
    async send() {
      this.adminInfo.avatar = this.imageUrl;
      await editInfoApi({
        name: this.adminInfo.name,
        avatar: this.adminInfo.avatar,
      });
      await this.setUser(this.adminInfo);

      this.editinfo = false;
      this.$message.success("成功修改个人信息", 1);
    },
    handleChange(info) {
      if (info.file.status === "uploading") {
        this.loading = true;
        return;
      }
      if (info.file.status === "done") {
        getBase64(info.file.originFileObj, () => {
          this.imageUrl = info.file.response.data[0];
          this.loading = false;
        });
      }
    },
    beforeUpload(file) {
      const isJpgOrPng =
        file.type === "image/jpeg" || file.type === "image/png";
      if (!isJpgOrPng) {
        this.$message.error("You can only upload JPG file!");
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("Image must smaller than 2MB!");
      }
      return isJpgOrPng && isLt2M;
    },
  },
};
</script>

<style lang="scss" scoped>
.avatar-uploader {
  width: 140px;
  height: 140px;
  .ant-upload {
    width: 128px;
    height: 128px;
    img {
      width: 100%;
      height: 100%;
    }
  }
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
.admin-info {
  display: flex;
  flex-direction: column;
  // align-items: center;
  gap: 0.5rem;

  .avatar {
    width: 5rem;
    height: 5rem;
    align-self: center;
    .avatar-img {
      width: 100%;
      height: 100%;
      border-radius: 50%;
      box-shadow: 2px 2px 5px #333333;
    }
  }
  .admin-name {
    align-self: center;
    font-size: 1.2rem;
    font-weight: bolder;
    color: black;
  }
  .admin-project {
    display: flex;
    // justify-content: space-around;
    .project-icon {
      margin-right: 10px;
    }
  }
}
.modal-name {
  margin: 10px;
}
.modal-avatar {
  margin: 10px;
  display: flex;
  .avatar-desc {
    align-self: flex-start;
    margin-right: 16px;
  }
}
</style>
